/*
* @name : 表格框架页组件
* @author : FuYaJuan
* @参数 { fieldList :  {Array} 表格字段 } 嵌套多级表头
* @参数 { queryParam :  {Object} 查询条件对象 }
* @参数 { api :  {Function} 查询接口函数 }
* @参数 { exportFn : {Function()} 分页中的导出函数 }
* @参数 { showIndex :  {Boolean} 是否显示序号，默认显示 }
* @参数 { showColumnSetting :  {Boolean} 是否开启动态列设置，默认显示 }
* @参数 { showExportBtn :  {Boolean} 是否显示导出按钮，默认显示 }
* @参数 { showCellClick :  {Boolean} 是否开启动态列设置，默认关闭 }
* @参数 { showCheckbox :  {Boolean} 是否显示复选框， 默认显示 }
* @参数 { page :  {Boolean} 是否带分页， 默认带分页 }
* @参数 { fixed :  {String} 列是否固定在左侧或者右侧，默认右侧 }
* @参数 { tableOptionWidth : {String} 最后一列的宽度 }
* @参数 { sortBy:后端翻译的表格字段要在fieldList中加上未翻译之前的字段名,否则会影响后端排序,不需要排序功能的列加上noSort:true 用法示例{ name: "组织机构", value: "orgName" ,sortBy:"orgId", noSort:true}}
* @事件 { getDataInit :  {Function()} 重新查询第一页的表格数据 }
* @事件 { handleCurrentChange :  {Function()} 重新查询当前页的表格数据 }
* @事件 { getMultipleSelection : {Function()} 获取表格多行选中的数据 }
* @version 1.0
* @edit: 2020/05/20
*/

<template>
    <div>
        <div class="s-o-t-wrap">
            <!--查询条件 -->
            <div class="search-wrap" v-if="searShow">
                <slot name="searchBar" />
            </div>
            <!-- 操作 -->
            <div class="table-top-option-wrap" v-if="btnShow">
                <div class="left">
                    <slot name="tableTopOptionLeft" />
                </div>
                <div class="right">
                    <slot name="tableTopOptionRight" />
                </div>
            </div>
            <!-- 表格 -->
            <div class="table-wrap" id="table-wrap">                
                <!-- {{ titleName }} -->
                <div class="right_title" v-if="titleShow">
                    <div>
                         <slot name="leftTitle" />
                    </div>
                    <div>
                        <slot name="rightTitle" />
                    </div>
                </div>
                <el-table ref="crudForm" :data="tableData" v-loading="loading" element-loading-text="加载中..."
                    @selection-change="handleSelectionChange" @sort-change="sortChange" @cell-click="cellClick"
                    :row-class-name="tableRowClassName" header-row-class-name="table-header"
                    :cell-class-name="tableRowClassName" :cell-style="columnStyle" :row-key="rowKey"
                    :tree-props="treeProps" stripe>
                    <el-table-column v-if="showIndex" type="index" width="70" align="left" :index="indexMethod" />
                    <el-table-column v-if="showCheckbox" type="selection" width="50" align="center" />
                    <el-table-column v-for="(item, index) in fieldList.filter((item) => !item.hidden)" :key="index"
                        :label="item.name" :align="item.clickable ? 'center' : 'left'" :width="item.width" show="true"
                        :v-if="item.show" :sortable="item.noSort ? false : 'custom'"
                        :sort-by="item.sortBy ? item.sortBy : item.value" show-tooltip-when-overflow>
                        <el-table-column v-for="(items, index) in item.list" :key="index" :label="items.name"
                            :align="items.clickable ? 'center' : 'left'" :width="items.width" show="true"
                            :v-if="items.show" :sortable="items.noSort ? false : 'custom'"
                            :sort-by="items.sortBy ? items.sortBy : items.value" show-tooltip-when-overflow>
                            <template slot-scope="scope">
                                <el-button v-if="items.type === 'link'" type="text" size="small"
                                    @click="items.clickFn(scope.row)">{{ scope.row[items.value] }}</el-button>
                                <template v-else>{{
                  items.formatter
                    ? items.formatter(scope.row)
                    : scope.row[items.value]
                }}</template>
                            </template>
                        </el-table-column>
                        <template slot-scope="scope">
                            <el-button v-if="item.type === 'link'" type="text" size="small"
                                @click="item.clickFn(scope.row)">{{ scope.row[item.value] }}</el-button>
                            <template v-else>{{
                item.formatter
                  ? item.formatter(scope.row)
                  : scope.row[item.value]
              }}</template>
                        </template>
                    </el-table-column>
                    <el-table-column :fixed="fixed" :width="Number(tableOptionWidth)" :label="tableOptionName"
                        align="left" v-if="showColumnHandle">
                        <template slot-scope="scope">
                            <slot name="tableOption" :row="scope.row" />
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="page-wrap-fixed" v-if="page" id="page-wrap-fixed">
            <el-pagination :current-page.sync="queryParam.current" :page-size="queryParam.size"
                :total="listInfo.pageTotal" :page-sizes="[10, 20, 50]"
                layout="total, sizes, prev, pager, next, jumper, slot" @size-change="handleSizeChange"
                @current-change="handleCurrentChange">
            </el-pagination>
        </div>
    </div>
</template>

<script>

import rightTitle from "./rightTitle.vue";
export default {
    name: "CrudForm",
    props: {
        // 表格字段配置
        fieldList: {
            type: Array,
            default: [],
        },
        // 查询条件
        queryParam: {
            type: Object,
            default: {},
        },
        // 获取数据的接口
        api: {
            type: Function,
        },
        // 导出
        exportFn: {
            type: Function,
        },
        // 最后一列显示的列名
        tableOptionName: {
            type: String,
            default: "操作",
        },
        // 是否带分页
        page: {
            type: Boolean,
            default: true,
        },
        // 表格是否显示序号
        showIndex: {
            type: Boolean,
            default: true,
        },
        // 表格是否显示复选框
        showCheckbox: {
            type: Boolean,
            default: true,
        },
        // 列是否固定在左侧或者右侧
        fixed: {
            type: String,
            default: "right",
        },
        // 最后一列的宽度
        tableOptionWidth: {
            type: String,
            default: "",
        },
        // 是否开启动态列设置
        showColumnSetting: {
            type: Boolean,
            default: true,
        },
        // 是否显示导出按钮
        showExportBtn: {
            type: Boolean,
            default: true,
        },
        // 是否显示操作列
        showColumnHandle: {
            type: Boolean,
            default: true,
        },
        columnNum: {
            type: String,
            default: "6",
        },
        searShow: {
            type: Boolean,
            default: true,
        },
        btnShow: {
            type: Boolean,
            default: true,
        },
        titleShow: {
            type: Boolean,
            default: true,
        },
        //不掉接口的data
        preData: {
            type: Array,
            default: () => []
        },
        //树性表格
        treeProps: {
            type: Object,
            default: () => { }
        },
        rowKey: {
            type: String,
            default: ""
        },
    },
    components: { rightTitle },
    data () {
        return {
            titleName: "",
            colOptions: [],
            colSelect: [],
            tableData: this.preData,
            exportData: {
                headers: [],
                values: [],
            },
            multipleSelection: [],
            loading: false,
            listInfo: {
                pageTotal: 0, // 总条数
                pageSizes: [5, 10, 20, 50, 100], // 分页数量列表
                query: {
                    // 查询条件
                    current: 1, // 当前页
                    size: 10, // 每页条数
                },
            },
            prj: {
                projectNum: 0,
                yearIncome: 0,
            },
        };
    },
    created () {
        this.api && this.getData(this.api);
        this.titleName = this.$route.meta.title;
    },
    mounted () {
        let elementResizeDetectorMaker = require("element-resize-detector");
        let tableWidth = document.getElementById("table-wrap");
        let pageWidth = document.getElementById("page-wrap-fixed");
        let erd = elementResizeDetectorMaker();
        erd.listenTo(tableWidth, function (element) {
            pageWidth.style.width = element.offsetWidth + "px";
        });
        for (let i = 0; i < this.fieldList.length; i++) {
            this.colSelect.push(this.fieldList[i].name);
            if (this.showColumnSetting) {
                if (this.colSelect.length > Number(this.columnNum)) {
                    continue;
                }
            }
            this.colOptions.push(this.fieldList[i].name);
        }
    },
    watch: {
        colOptions (colArr) {
            let self = this;
            for (let i in self.fieldList) {
                if (colArr.indexOf(self.fieldList[i].name) === -1) {
                    self.fieldList[i].show = false;
                } else {
                    self.fieldList[i].show = true;
                }
            }
        },
    },
    beforeUpdate () {
        this.$nextTick(() => {
            this.$refs.crudForm.doLayout();
        });
    },
    methods: {
        indexMethod (index) {
            let idx = index >= 9 ? index + 1 : "0" + (index + 1);
            return idx;
        },
        tableRowClassName ({ row, rowIndex }) {
            if (rowIndex % 2 == 1) {
                return "warning-row";
            } else {
                return "success-row";
            }
            return "";
        },
        // 分页-刷新
        refresh () {
            this.getData(this.api);
        },
        // 导出
        exportTable () {
            if (!this.tableData.length) {
                this.$message({
                    showClose: true,
                    message: "列表数据为空,无法导出!",
                    type: "warning",
                });
                return;
            }
            this.exportData.headers = [];
            this.exportData.values = [];
            for (let i = 0; i < this.fieldList.length; i++) {
                if (this.fieldList[i].show == true) {
                    this.exportData.headers.push(this.fieldList[i].name);
                    this.exportData.values.push(this.fieldList[i].value);
                }
            }
            this.exportFn ? this.exportFn() : null;
        },
        // 表格多行选中
        handleSelectionChange (val) {
            this.multipleSelection = val;
        },
        // 获取表格多行选择的数据
        getMultipleSelection () {
            this.$emit("getMultipleSelection",this.multipleSelection)
            return this.multipleSelection;
        },
        // 调用接口 获取数据
        getData (api) {
            this.loading = true;
            return new Promise((resolve, reject) => {
                api(this.handleParams())
                    .then((res) => {
                        this.loading = false;
                        if (
                            res.code === "000000" ||
                            res.code == "10000" ||
                            res.code == 200
                        ) {
                            const d = res.data;
                            if (d.records) {
                                this.tableData = d.records;
                            } else {
                                this.tableData = d;
                            }
                            if (d.list) {
                                this.tableData = d.list;
                            }
                            this.listInfo.pageTotal = parseInt(d.total);
                            this.queryParam.size = d.pageSize || d.size;
                            this.queryParam.current = d.pageNum || d.current;
                            this.prj = {
                                projectNum: 0,
                                yearIncome: 0,
                            };
                            if (this.$route.meta.title == "项目收入统计") {
                                this.prj.projectNum += d.projectNum;
                                this.prj.yearIncome += d.yearIncome;
                            }
                        } else {
                            this.$message.error(res.data);
                        }
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$message.error("数据加载失败!");
                    });
            });
        },
        // 重新查询第一页的表格数据
        getDataInit () {
            this.queryParam.current = 1;
            this.getData(this.api);
            this.$emit("getDataInit");
        },
        // 处理接口调用所需的参数
        handleParams () {
            const obj = {};
            for (const key in this.queryParam) {
                if (this.queryParam[key] || this.queryParam[key] === 0) {
                    obj[key] = this.queryParam[key];
                }
            }
            return { ...this.listInfo.query, ...obj };
        },
        // pageSize 改变时会触发
        handleSizeChange (val) {
            const query = this.queryParam;
            query.size = val; // 每页条数
            query.current = 1; // 每页条数切换，重置当前页
            this.getData(this.api);
        },
        // currentPage 改变时会触发
        handleCurrentChange (val) {
            // console.log(val);
            this.queryParam.current = val; // 当前页
            this.getData(this.api);
        },
        // 列排序
        sortChange (column) {
            if (column.order === "ascending") {
                this.queryParam.order = "asc";
            } else {
                this.queryParam.order = "desc";
            }
            this.getData(this.api);
        },
        // 设置点击列样式
        columnStyle (row, column, rowIndex, columnIndex) {
            if (row.column.align == "is-center") {
                return "color: #23a4a4; cursor: pointer;";
            } else {
                return "";
            }
        },
        // 表格点击事件
        cellClick (row, column, cell, event) {
            this.$emit("cell-click", row, column, cell, event);
        },
    },
};
</script>

<style lang="scss" scoped>
// @import "@/styles/element-variables.scss";
.search-wrap {
    // @include background_color("el-form-bg");
}
>>> .el-table tr {
    height: 40px;
}
.s-o-t-wrap {
    margin-bottom: 45px;
}

.search-wrap {
    padding: 18px 12px 8px;

    >>> button {
        width: 90px;
        height: 30px;
        border-radius: 3px;
    }
}
.right_title {
    // @include background_color("table-top-title");
    // @include font_color("table-top-title-color");
    width: 100%;
    height: 40px;
    line-height: 40px;
    font-size: 18px;
    padding: 0 30px;
    /* background-color: #374492; */
    // @include background_color("table-top-title");
    // @include font_color("table-top-title-color");
    color: #fff;
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    margin-bottom: -10px;
    font-size: 14px;
}

.search-wrap >>> .el-form--inline .el-form-item {
    margin-bottom: 10px;
    margin-right: 20px;

    .el-form-item__label {
        display: inline-block;
        // width: 70px;
        text-align: right;
        padding-right: 10px;
        line-height: 30px;
    }

    .el-form-item__content {
        line-height: 30px;
    }

    .el-input {
        width: 180px;
    }
    button {
        margin-top: 0;
    }
}

.table-top-option-wrap {
    margin: 20px 20px 14px;
    overflow: hidden;

    .left {
        float: left;

        >>> .el-button--primary {
            width: 148px;
            height: 32px;
            border-radius: 2px;
        }
    }
    .right {
        float: right;

        >>> .el-button {
            width: 120px;
            height: 32px;
            border-radius: 2px;
        }
    }
}

.table-wrap {
    padding: 0 20px;
    .el-table th {
        padding: 2px 0;
    }
}
.table-wrap >>> .table-header {
    background-color: #f1f1f1;
    color: #ffffff;
    font-weight: bold;

    th {
        background-color: #2a377b;
    }
}
.table-wrap >>> .table-body-td {
    padding: 3px 0;
}
</style>
